package leetcode;

import java.util.Arrays;

/**
 * 59.
 * Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
 */
public class SpiralMatrix {
    // 类似于迷宫，小蚂蚁采取右下坐上的顺序走迷宫，
    // 如果碰壁则换方向，直至走完迷宫，
    // 出迷宫的条件是 curNum = maxNum
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int curNum = 1;
        int maxNum = n * n;
        int row = 0, column = 0;
        int[][] direction = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int[] direMax = {n, n, n, n};
        while(curNum <= maxNum){
            result[row][column] = curNum;
            curNum++;
            if (column + 1 == direMax[0]){
                direMax[0]--;
                row++;
            }
            if (row + 1 == direMax[1]){
                direMax[1]--;
                column++;
            }
            
        }
        return result;
    }

    public static void main(String[] args) {
        SpiralMatrix s = new SpiralMatrix();
        int[][] arr = s.generateMatrix(5);
        for (int[] a: arr) {
            System.out.println(Arrays.toString(a));
        }
    }
}
